package at.fhj.itm11.forum.data.impl;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import at.fhj.itm11.forum.data.UserDAO;
import at.fhj.itm11.forum.model.User;

@Named
@Stateless
public class UserDAOImpl implements UserDAO {

	@Inject
	private EntityManager em;

	public User findById(Long id) {
		return em.find(User.class, id);
	}

	public User findByUsername(String username) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<User> criteria = cb.createQuery(User.class);
		Root<User> user = criteria.from(User.class);

		criteria.select(user).where(cb.equal(user.get("username"), username));
		return em.createQuery(criteria).getSingleResult();
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

}
